package com.dx.VegetableOxygenBarBackEnd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dx.VegetableOxygenBarBackEnd.common.BaseResponse;
import com.dx.VegetableOxygenBarBackEnd.common.DeleteRequest;
import com.dx.VegetableOxygenBarBackEnd.common.ErrorCode;
import com.dx.VegetableOxygenBarBackEnd.common.ResultUtils;
import com.dx.VegetableOxygenBarBackEnd.exception.BusinessException;
import com.dx.VegetableOxygenBarBackEnd.model.domain.dto.TeamQuery;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.Team;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.User;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.UserTeam;
import com.dx.VegetableOxygenBarBackEnd.model.domain.request.TeamAddRequest;
import com.dx.VegetableOxygenBarBackEnd.model.domain.request.TeamJoinRequest;
import com.dx.VegetableOxygenBarBackEnd.model.domain.request.TeamQuitRequest;
import com.dx.VegetableOxygenBarBackEnd.model.domain.request.TeamUpdateRequest;
import com.dx.VegetableOxygenBarBackEnd.model.domain.vo.TeamUserVo;
import com.dx.VegetableOxygenBarBackEnd.model.domain.vo.UserVo;
import com.dx.VegetableOxygenBarBackEnd.service.TeamService;
import com.dx.VegetableOxygenBarBackEnd.service.UserService;
import com.dx.VegetableOxygenBarBackEnd.service.UserTeamService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/team")
//跨域问题解决、默认全部ip都可以访问，
@CrossOrigin(origins = "https://danma.icu", allowCredentials = "true")
//@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class TeamController {

    @Resource
    private UserService userService;
    @Resource
    private TeamService teamService;
    @Resource
    private UserTeamService userTeamService;

    /**
     * 创建队伍
     *
     * @param teamAddRequest 队伍参数
     * @return 创建的队伍id
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest httpServletRequest) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(httpServletRequest);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamid = teamService.addTeam(team, loginUser);
        if (teamid <= 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "add error");
        }
        return ResultUtils.success(teamid);
    }


    /**
     * 修改队伍
     *
     * @param teamUpdateRequest  修改队伍的参数
     * @param httpServletRequest
     * @return true
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest httpServletRequest) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(httpServletRequest);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        boolean update = teamService.updateTeam(teamUpdateRequest, loginUser);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "update error");
        }
        return ResultUtils.success(true);
    }

    /**
     * 加入队伍
     *
     * @param teamJoinRequest
     * @param httpServletRequest
     * @return
     */
    @PostMapping("join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest httpServletRequest) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(httpServletRequest);
        boolean res = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(res);
    }

    /**
     * 退出队伍
     *
     * @return
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest httpServletRequest) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(httpServletRequest);
        boolean res = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(res);
    }

    /**
     * 解散队伍
     *
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest httpServletRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Long teamId = deleteRequest.getId();
        User loginUser = userService.getLoginUser(httpServletRequest);
        boolean res = teamService.deleteTeam(teamId, loginUser);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return ResultUtils.success(res);
    }

    /**
     * 查询单个队伍
     *
     * @param id 队伍id
     * @return 队伍
     */
    @GetMapping("/get")
    public BaseResponse<Team> getTeam(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "该队伍不存在");
        }
        return ResultUtils.success(team);
    }

    /**
     * 展示查询队伍列表、、全部符合的都展示
     *
     * @param teamQuery 查询队伍参数
     * @return 队伍列表
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVo>> listTeam(TeamQuery teamQuery, HttpServletRequest httpServletRequest) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        boolean isAdmin = userService.isAdminUser(httpServletRequest);
        // 获取队伍列表
        List<TeamUserVo> teamsList = teamService.listTeam(teamQuery, isAdmin);
        if (CollectionUtils.isEmpty(teamsList)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "暂无队伍信息，你先创建一个吧~~");
        }
        // 收集队伍列表id
        setIsHasJoinTeam(httpServletRequest, teamsList);
        final List<Long> teamIdList = teamsList.stream().map(TeamUserVo::getId).collect(Collectors.toList());
        setTeamListHasJoinNum(teamsList, teamIdList);
        return ResultUtils.success(teamsList);
    }

    /**
     * 想teamList列表添加是否已经加入这个队伍的字段的判断    hasJoin   True/false
     *
     * @param httpServletRequest
     * @param teamsList
     */

    private void setIsHasJoinTeam(HttpServletRequest httpServletRequest, List<TeamUserVo> teamsList) {
        List<Long> userIdList = teamsList.stream().map(TeamUserVo::getId).collect(Collectors.toList());
        QueryWrapper<UserTeam> teamUserQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLoginUser(httpServletRequest);
            if (loginUser != null) {
                teamUserQueryWrapper.eq("userId", loginUser.getId())
                        .in("teamId", userIdList);
                // 查询满足条件的数据，满足：1、当前登录用户的队伍 2、队伍的id要在数据库里
                List<UserTeam> userTeamList = userTeamService.list(teamUserQueryWrapper);
                // 已经加入队伍的id集合
                Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
                // 遍历判断 当前用户加入的这个队伍的id，是否是在队伍列表中
                teamsList.forEach(team -> {
                    boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                    team.setHasJoin(hasJoin);
                });
            }
        } catch (Exception e) {
            log.error("Error occurred while processing listTeam", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取队伍列表失败");
        }
    }

    /**
     * 抽取的方法
     * 封装已经加入队伍的人数
     *
     * @param teamsList
     * @param teamIdList
     */

    private void setTeamListHasJoinNum(List<TeamUserVo> teamsList, List<Long> teamIdList) {
        // 3、查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamsList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
    }


    /**
     * 获取我加入的队伍
     *
     * @param teamQuery
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVo>> listMyJoin(TeamQuery teamQuery, HttpServletRequest httpServletRequest) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(httpServletRequest);
        // 查询用户加入的队伍
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        if (CollectionUtils.isEmpty(userTeamList)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "你还没有加入任何队伍。");
        }
        // 获取队伍ID列表
        List<Long> teamIdList = userTeamList.stream()
                .map(UserTeam::getTeamId)
                .distinct() // 去除重复的 teamId
                .collect(Collectors.toList());
        // 将 teamIdList 设置到查询条件中
        teamQuery.setIdList(teamIdList);
        // 查询队伍列表
        List<TeamUserVo> teamsList = teamService.listTeam(teamQuery, true);
        if (CollectionUtils.isEmpty(teamsList)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "暂无队伍信息，你先创建一个吧~~");
        }
        // 处理队伍的人数信息及用户是否加入
        setTeamListHasJoinNum(teamsList, teamIdList);
        setIsHasJoinTeam(httpServletRequest, teamsList);
        // 返回队伍信息
        return ResultUtils.success(teamsList);
    }

    /**
     * 获取我创建的队伍
     *
     * @param teamQuery
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/list/my")
    public BaseResponse<List<TeamUserVo>> listMyTeams(TeamQuery teamQuery, HttpServletRequest httpServletRequest) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(httpServletRequest);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVo> teamsList = teamService.listTeam(teamQuery, true);
        if (CollectionUtils.isEmpty(teamsList)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "暂无队伍信息，你先创建一个吧~~");
        }
        final List<Long> teamIdList = teamsList.stream().map(TeamUserVo::getId).collect(Collectors.toList());
        setTeamListHasJoinNum(teamsList, teamIdList);
        setIsHasJoinTeam(httpServletRequest, teamsList);
        return ResultUtils.success(teamsList);
    }

    /**
     * 获取当前队伍的所有用户信息列表
     *
     * @param teamId 队伍id
     * @return 用户列表
     */
    @GetMapping("/list/teamuser")
    public BaseResponse<List<UserVo>> getTeamUsersByTeamId(long teamId) {
        if (teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserVo> userVoList = teamService.listUserInTeam(teamId);
        return ResultUtils.success(userVoList);
    }

    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listTeamByPage(TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> teamPage = teamService.page(page, queryWrapper);
        return ResultUtils.success(teamPage);
    }
}
